package pers.ree.demo.concurrent.atomic;

import java.util.concurrent.atomic.LongAccumulator;

public class LongAccumulatorDemo {

    private LongAccumulator longAccumulator = new LongAccumulator((a, b)->a+b, 0);

    // 不使用lamda表达式，直接传一个LongBinaryOperator的匿名实现类也可以
//    private LongAccumulator longAccumulator = new LongAccumulator(new LongBinaryOperator() {
//        @Override
//        public long applyAsLong(long left, long right) {
//            return left + right;
//        }
//    }, 0);


    public void sum() {
        for (int i=0; i<10000; i++) {
            longAccumulator.accumulate(1);
        }

        System.out.println(Thread.currentThread().getName() + ", " + longAccumulator.longValue());
    }

    public static void main(String[] args) {
        LongAccumulatorDemo demo = new LongAccumulatorDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.sum();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.sum();
            }
        }).start();
    }
}
